<!--
  移动签批->公文详情->发文->修改公文要素
-->
<template>
  <view>
    <van-popup v-model="showCompo" closeable round position="bottom" :style="{ height: '100%' }"
               @click-close-icon="toClose" @click-overlay="toClose">
      <van-row type="flex" justify="center">
        <van-col offset="1" span="8">
          <van-cell value="修改公文要素"/>
        </van-col>
      </van-row>
      <van-form>
        <van-collapse v-model="tableShow" accordion :border="border">
          <van-collapse-item icon="label-o" title="公文要素" title-class="text-bold" name="jbxx">
            <van-cell ref="mj" required is-link title="密级" :value="this.dict.getDictNameByDictCode('mj',formData.secrecyLevel)"
                      @click="show = true"/>
            <van-action-sheet v-model="show" :actions="mj" cancel-text="取消" @select="onSelect"/>
            <van-cell is-link title="紧急程度" required
                      :value="this.dict.getDictNameByDictCode('swjjcd',formData.emergencyLevel)" @click="show1 = true"/>
            <van-action-sheet v-model="show1" :actions="hj" cancel-text="取消" @select="onSelect1"/>

            <van-field ref="title" v-model="formData.title" required label="文件标题" placeholder="请输入"
                       input-align="right" autosize rows="1" type="textarea" />

            <van-field label="办结时限" :value="formData.endlineTime" @click="showCalendar = true" placeholder="请选择"
                       input-align="right" is-link/>
            <van-calendar v-model:showCalendar="showCalendar" :show-confirm="false" @confirm="onConfirm"/>

            <van-cell title="主办处室" :value="formData.directDeptNames" is-link @click="showOrgTreeSheet('mainTo')"/>
            <!-- forwardType:mainTO：主办，copyTo：抄送 -->
            <orgTreeDirect ref="mainTo" :showOrgTree="showDirectDeptTree" :nodeData="nodeData" :formDetail="formData"
                           :forwardType="treeForwardType" @closeOrgTreeSheet="closeOrgTreeSheet"></orgTreeDirect>

            <van-cell title="协办处室" :value="formData.coDeptNames" forwardType="copyTo" is-link
                      @click="showOrgTreeSheet('copyTo')"/>
            <orgTreeCo ref="copyTo" :showOrgTree="showCoDeptTree" :nodeData="nodeData" :formDetail="formData"
                       :forwardType="treeForwardType" @closeOrgTreeSheet="closeOrgTreeSheet"></orgTreeCo>

            <van-field ref="lwdept" v-model="formData.fwDeptName" required label="来文单位" placeholder="请输入"
                       input-align="right"/>

            <van-cell is-link title="来文编号" v-model="lwcode" @click="showGenerate('lw')"/>
            <generate @closeGenerate="closeGenerate" @saveGenerate="saveGenerate" :tagType="tagType"
                      :showGenerate="showGenLw" :generateParamObject="formData"></generate>

            <van-cell ref="swbh" is-link required title="收文编号" v-model="swcode" @click="showGenerate('sw')"/>
            <generate @closeGenerate="closeGenerate" @saveGenerate="saveGenerate" :tagType="tagType"
                      :showGenerate="showGenSw" :generateParamObject="formData"></generate>

            <van-field label="收文时间" :value="formData.swTime" @click="showCalendarSw = true" placeholder="请选择"
                       input-align="right" is-link/>
            <van-calendar v-model:showCalendar="showCalendarSw" :show-confirm="false" @confirm="onConfirmSw"/>

            <van-field v-model="formData.remark" label="备注" placeholder="请输入" input-align="right"/>

          </van-collapse-item>
          <van-collapse-item icon="font-o" title="已附加公文" title-class="text-bold" name="zwjfj">
            <view class="opinion" v-if="relation.length>0 ">
              <text class="opinion-left">附加公文</text>
              <view class="opinion-right">
                <text v-for="(item,index) in relation">{{ item.title }}</text>
              </view>
            </view>
          </van-collapse-item>
        </van-collapse>
      </van-form>

      <view class="padding-top-lg padding-bottom-lg">
        <van-row type="flex" justify="space-around">
          <van-col span="10">
            <van-button type="info" round plain hairline block @click="toClose">取消</van-button>
          </van-col>
          <van-col span="10">
            <van-button type="info" round block @click="toEdit">确定</van-button>
          </van-col>
        </van-row>
      </view>
    </van-popup>
  </view>
</template>

<script>
import forward from 'pages/caac/components/sjswDoc/compo-forward';
import orgTreeDirect from 'pages/caac/components/sjswDoc/compo-orgtree';//单位选择组件
import orgTreeCo from 'pages/caac/components/sjswDoc/compo-orgtree';//单位选择组件
import drafter from 'pages/caac/components/common/compo-drafter';//拟稿人选择
import generate from 'pages/caac/components/sjswDoc/compo-generate';

export default {
  components: {
    forward,
    orgTreeDirect,
    orgTreeCo,
    drafter,
    generate
  },
  props: {
    showEdit: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    showEdit(val) {
      this.showCompo = val
    },
  },
  data() {
    return {
      swcode: '',       // 收文编号
      lwcode: '',       // 来文编号
      showGenLw: false,       // generate来文显示
      showGenSw: false,       // generate收文显示
      tagType: '',          // sw-收文字号，lw-来文字号
      paramObject: {},      // 用于回显

      showCompo: false,//组件是否显示
      showCalendar: false,//日历组件显示
      showCalendarSw: false,//收文时间显示
      showDirectDeptTree: false,//主办部门是否显示
      showCoDeptTree: false,    //协办部门是否显示

      showOrgtree: false,//显示机构树
      showDrafter: false,//拟稿人组件

      dictSecrecyLevel: [],//密级字典数组
      dictEmergencyLevel: [],//紧急程度字典数组
      mj: [],
      hj: [],
      relation: [],//附加公文列表
      ready: false, // 这里用于自主控制loading加载状态，避免异步正在加载数据的空档显示“暂无数据”
      showOrg: false,
      formData: {},//表单数据
      showPopup: false,
      border: false,
      show: false,
      show1: false,
      tableShow: "jbxx",

      //主送显示和隐藏哪些节点
      nodeData: {
        showNode: '001002005,001002006,001002008,001002007,001002002,001002009,001002001,001002010,001002003,001002004',//显示的节点
        hideNode: '',//隐藏的节点
      },
      treeForwardType: '',

    };
  },
  mounted() {
    this.getDict()//获取字典项
    this.getShowDept()//获取要显示的组织机构
  },
  methods: {
    //主办和协办组件显示
    showOrgTreeSheet(type) {
      if (type == 'mainTo') {
        this.treeForwardType = 'mainTo'
        this.showDirectDeptTree = true
        this.$refs.mainTo.getOrgTree(this.formData.directDeptIds)
      } else if (type == 'copyTo') {
        this.treeForwardType = 'copyTo'
        this.showCoDeptTree = true
        this.$refs.copyTo.getOrgTree(this.formData.coDeptIds)
      }
    },
    /**
     * 子组件调用，通知父组件关闭当前子组件
     * @param {Object} orgInfo 选中的数组对象
     * forwardType   mainTo：主办，copyTo：协办
     * {forwardType:this.forwardType,orgName:this.deptName.toString(),deptCode:this.deptCode.toString()}
     */
    closeOrgTreeSheet(orgInfo) {
      console.log("orgInfo=============" + JSON.stringify(orgInfo))
      if (this.util.isNotEmpty(orgInfo.forwardType)) {
        if (orgInfo.forwardType == 'mainTo') {//主办
          this.formData.directDeptNames = ''
          this.formData.directDeptIds = ''
          if (this.util.isNotEmpty(orgInfo.deptCode)) {
            this.formData.directDeptNames = orgInfo.orgName
            this.formData.directDeptIds = orgInfo.deptCode
          }
          this.showDirectDeptTree = false
        } else if (orgInfo.forwardType == 'copyTo') {//抄送
          this.formData.coDeptNames = ''
          this.formData.coDeptIds = ''
          if (this.util.isNotEmpty(orgInfo.deptCode)) {
            this.formData.coDeptNames = orgInfo.orgName
            this.formData.coDeptIds = orgInfo.deptCode
          }
          this.showCoDeptTree = false
        }
      }
    },

    // 显示字号组件
    //lw-来文编号
    //sw-收文编号
    showGenerate(type) {
      this.tagType = type
      if (this.tagType == 'lw') {
        this.showGenLw = true
      } else {
        this.showGenSw = true
      }
      this.showGen = true
      this.paramObject.swId = this.formData.UUID
      this.paramObject.swWordId = this.formData.SW_WORD_ID
      this.paramObject.swWord = this.formData.SW_WORD
      this.paramObject.swNum = this.formData.SW_NUM
      this.paramObject.swYear = this.formData.SW_YEAR
    },
    // 关闭字号组件
    closeGenerate() {
      this.showGenLw = false
      this.showGenSw = false
    },
    // 保存字号
    saveGenerate(data) {
      //{"type":"lw","lwWord":"123","swWord":null,"swYear":2022,"lwYear":2022,"swNum":null,"lwNum":"132","swWordId":null}
      if (data.type == 'lw') {
        this.formData.fwWord = data.lwWord
        this.formData.fwYear = data.lwYear
        this.formData.fwNum = data.lwNum
        this.lwcode = this.generateCode(data.lwWord, data.lwYear, data.lwNum)
      } else if (data.type == 'sw') {
        this.formData.swWord = data.swWord
        this.formData.swYear = data.swYear
        this.formData.swNum = data.swNum
        this.formData.swWordId = data.swWordId
        this.swcode = this.generateCode(data.swWord, data.swYear, data.swNum)
      }
      this.showGenLw = false
      this.showGenSw = false
    },
    // 生成编号
    generateCode(word, year, num) {
      if (word != null && word != ''
              && year != null && year != ''
              && num != null && num != '') {
        return word + '〔' + year + '〕' + num + '号'
      }
    },

    //拟稿人
    showDrafterSheet() {
      this.showDrafter = true
    },
    //关闭拟稿人组件
    closeDrafterSheet(userInfo) {
      //userInfo: {"userId":"4926","userName":"高萌"}
      this.formData.drafterId = userInfo.userId
      this.formData.drafterName = userInfo.userName
      this.showDrafter = false
    },
    //日期组件确定事件
    onConfirm(date) {
      const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      this.showCalendar = false
      this.formData.endlineTime = formatDate(date)
    },
    onConfirmSw(date) {
      const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      this.showCalendarSw = false
      this.formData.swTime = formatDate(date)
    },

    //密级
    onSelect(item) {
      //item: {"name":"无","dictItemCode":"1"}
      this.formData.secrecyLevel = item.dictItemCode
      // this.formData.secrecyLevelName = item.name
      this.show = false;
    },
    //缓急
    onSelect1(item) {
      this.formData.emergencyLevel = item.dictItemCode
      // this.formData.emergencyLevelName = item.name
      this.show1 = false;
    },

    //取消按钮
    toClose() {
      this.$emit('closeEdit', this.showEdit);
    },
    //确定按钮
    toEdit() {
      this.saveelement()
    },
    // 表单校验
    validateForm() {
      if (this.util.isEmpty(this.formData.secrecyLevel)) {
        this.$refs.mj.focus()
        this.$toast('请选择密级')
        return false
      }
      if (this.util.isEmpty(this.formData.title)) {
        this.$refs.title.focus()
        this.$toast('请填写标题')
        return false
      }
      if (this.util.isEmpty(this.formData.fwDeptName)) {
        this.$refs.lwdept.focus()
        this.$toast('请填写来文单位')
        return false
      }
      if (this.util.isEmpty(this.swcode)) {
        this.$refs.swbh.focus()
        this.$toast('收文编号不能为空')
        return false
      }

      return true;
    },
    //修改公文要素
    saveelement() {
      console.log("修改公文要素==>: " + JSON.stringify(this.formData));
      if (this.validateForm()) {
        this.$httploading({
          //修改呈批件接口和发文发电不一样
          url: this.$http.adornUrl(`/caac/oa/doc/sjsw/sjswSaveElement`),
          method: 'post',
          params: this.$http.adornParams({
            "systemKey": this.cache.get('userInfo').systemKey,
            "systemFlag": this.cache.get('userInfo').systemFlag
          }),
          data: JSON.stringify(this.formData)

        }).then(({data}) => {
          console.log("修改公文要素data: " + JSON.stringify(data));
          if (data.code == 200) {
            this.$toast('修改公文要素成功')
            this.$emit('closeEdit', this.showEdit);
            this.$emit('refreshBtnGroup', true)//修改成功后通知父组件重新加载数据
            // console.log("this.formData: " + JSON.stringify(this.formData));
          }
        })
      }
    },
    //父组件点击修改公文要素时调用获取详情回显到表单
    editGw(proInstId) {
      console.log("获取公文要素详情" + proInstId);
      this.$httploading({
        url: this.$http.adornUrl(`/caac/oa/doc/sjsw/sjswproInstId/` + proInstId),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        console.log("获取公文要素详情data: " + JSON.stringify(data));
        if (data.code == 200) {
          this.formData = data.data
          this.getRelation(data.data.extendIdForRelate)
        }
      })
    },
    //获取附加公文
    getRelation(extendIdForRelate) {
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/mhjComponent/relationfile/relation`),
        method: 'get',
        params: this.$http.adornParams({
          'docId': extendIdForRelate,
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        //[{"id":"1c0962f8839d46f792f84e5c89c96f14","title":"ppap","relateDocId":"4ec205b8334446f9b932d0fcb3896bc8","proInstId":"4ec205b8334446f9b932d0fcb3896bc8"},{"id":"2f4aa437ecba4c748bff911f03667147","title":"py","relateDocId":"86d30c881c494b468534685bb0746174","proInstId":"86d30c881c494b468534685bb0746174"}]
        if (data.code == 200) {
          if (data.data != null) {
            this.relation = data.data
          }
        }
        console.log("附加公文: " + JSON.stringify(data));
      })
    },
    //获取要显示的组织机构代码
    getShowDept() {
      this.$http({
        url: this.$http.adornUrl(`/caac/oa/doc/sw/hidedepts`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,//固定值
          'systemFlag': this.cache.get('userInfo').systemFlag//固定值
        })
      }).then(({data}) => {
        if (data.code == 200) {
          if (data.data != null) {
            this.nodeData.showNode = data.data.hideDepts
            this.nodeData.hideNode = ''//要隐藏的节点
          }
        }
      })
    },
    //获取需要的字典项
    getDict() {
      this.dictSecrecyLevel = this.cache.get('mj')//密级
      //给van-action-sheet 赋值
      this.mj = []
      this.dictSecrecyLevel.forEach((item) => {
        this.mj.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })
      this.dictEmergencyLevel = this.cache.get('jjcd')//紧急程度
      this.hj = []
      this.dictEmergencyLevel.forEach((item) => {
        this.hj.push({name: item.dictItemName, dictItemCode: item.dictItemCode})
      })
    },


  },


};
</script>

<style scoped>
  /* 意见相关样式 */
  .opinion{
    display: flex;
    flex-direction: column;
    margin: 0 32rpx;
    padding: 20rpx 0rpx;
    overflow: hidden;
    font-size: 28rpx;
    line-height: 24px;
    border-bottom: 1px solid #ebedf0;

  }
  .opinion .opinion-left{
    text-align: left;
    color: #323233;
  }
  .opinion .opinion-right{
    text-align: right;
    color: #969799;
  }
	.van-cell__title {
		min-width: 55%;

		span {
			display: inline-block;
			text-align: left;
			word-break: break-all;
		}
	}

	/deep/ .van-collapse-item__content {
		padding: 0px;
		color: #969799;
		font-size: 14px;
		line-height: 1.5;
		background-color: #fff;
	}

	/deep/ .van-field__label {
		color: #323233;
		min-width: 50%;

		span {
			display: inline-block;
			text-align: left;
			word-break: break-all;
		}
	}

	/deep/ .van-field__control {
		font-size: 14px;
		color: #969799;
	}
</style>
